#pragma once

#include <iostream>
#include <vector>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <set>
#include <functional>
#include "InetAddr.hpp"
#include "Threadpool.hpp"

using task_t = std::function<void()>;
class MessageRoute
{
private:
    bool IsExists(const InetAddr &addr)
    {
        for (auto a : _online_user)
        {
            if (a == addr)
                return true;
        }
        return false;
    }

public:
    MessageRoute()
    {
    }
    void AddUser(const InetAddr &addr)
    {
        if (IsExists(addr))
            return;

        LOG(INFO, "---------ADD user------");
        _online_user.push_back(addr);
    }
    void DelUser(const InetAddr &addr)
    {
        for (auto iter = _online_user.begin(); iter != _online_user.end(); iter++)
        {
            if (*iter == addr)
            {
                _online_user.erase(iter);
                break;
            }
        }
    }
    void RouteHelper(int sockfd, const std::string message)
    {
        // 2.进行消息转发
        for (auto& user : _online_user)
        {
            struct sockaddr_in who = user.Addr();
            ::sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)(&who), sizeof(user.Addr())); //??????
        }
    }
    void Route(int sockfd, const std::string message, const InetAddr who)
    {
        // 1.用户首次发消息，将用户插入在线用户中
        AddUser(who);
        // 1.1用户要退出

        if (message == "Q" || message == "QUIT")
        {
            DelUser(who);
        }

        // 2.构建任务对象
        task_t t = std::bind(&MessageRoute::RouteHelper, this, sockfd, message);
        ThreadPool<task_t>::GetInstance()->Enqueue(t);
    }

    ~MessageRoute()
    {
    }

private:
    std::vector<InetAddr> _online_user;
};